<template>
<div class="custom-search">
  <h4>
    <backBtn type="business"></backBtn>
    {{$t('customer.exportTaskList')}}
    <span @click.stop="search" class="refresh"><i class="iconfont icon-shuaxin"></i></span>
  </h4>
  <div class="table-wrap">
    <div class="prompt">
      ﻿{{$t('business.exportTaskPrompt' + exportType, tipNum)}}
    </div>
    <common-table :tableHead="tableHead" :data="tableData" :limit="20" :pagination="pagination" @operate="operate" @turnPage="search">
    </common-table>
  </div>
</div>
</template>
<script>
  import CommonTable from '../config/robotConfig/base/CommonTable.vue'
  import backBtn from '@/components/public-modules/side-bar/BackSideBar.vue'
  export default {
    name: 'ExportTask',
    data () {
      return {
        pagination: {
          currentPage: 0,
          count: 0,
          totalPage: 0
        },
        searchObj: {
          page: 1,
          limit: 20
        },
        tipNum: {
          maxNum: '',
          taskNum: ''
        },
        rules: {
          name: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ]
        },
        tableData: [],
        tableHead: [
          {prop: 'createTime', label: this.$t('public.createTime')},
          {prop: 'downloadAgents', label: this.$t('business.downloadAgents')},
          {prop: 'size', label: this.$t('business.exportSize')},
          {prop: 'statusName', label: this.$t('business.exportStatus')},
          {prop: 'operate', label: this.$t('public.operate'), special: 'operateContent'}
        ],
        exportType: this.$store.state.isRealTimeExport ? 'real' : '' // real实时导出任务
      }
    },
    components: {
      CommonTable,
      backBtn
    },
    methods: {
      operate (event) {
        let type = event.type
        let data = event.val
        if (type === 'delete') {
          this.delete({_id: data._id})
        } else if (type === 'download') {
          this.$store.commit('SET_FILEDOWNLOAD', {path: data.path, isSession: true})
        } else if (type === 'repeatExport') {
          this.repeatExport({_id: data._id})
        }
      },
      delete (data) {
        this.$confirm(this.$t('business.businessDeleteTip'), this.$t('public.delete'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        })
          .then(() => {
            this.$store.dispatch('deleteExportTask', data)
              .then(resp => {
                if (resp.success) {
                  this.search()
                  this.$message({
                    type: 'success',
                    message: this.$t('message.deleteSucc')
                  })
                }
              })
          })
      },
      repeatExport (data) {
        this.$store.dispatch('reExportTask', data).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('business.submitSuccess'))
            this.search()
          }
        })
      },
      search (page) {
        this.searchObj.page = typeof page === 'number' ? page : 1
        this.$store.dispatch('getExportTaskList', this.searchObj).then((res) => {
          this.tableData = []
          if (res.success) {
            let agents = this.$agentsMap() || {}
            // let sessionId = this.$store.state.session.sessionId
            this.pagination.count = res.count
            this.pagination.currentPage = this.searchObj.page
            let list = res.list || []
            for (let i = 0; i < list.length; i++) {
              let one = list[i]
              // ready 等待处理
              // export wait 正在导出 / 正在处理
              // exportSuccess 导出成功
              // exportFailed 导出失败
              // expired 已失效
              one.downloadAgents = (one.downloadAgents || [one.createUser]).map((item) => {
                let agent = agents[item]
                return agent ? `${agent.displayName}[${agent.exten}]` : ''
              }).join('，')
              if (one.status === 'exportFaild' || one.status === 'failure') {
                one.statusName = this.$t('webchat.exportError')
                one.operate = [{name: this.$t('business.repeatExport'), type: 'repeatExport'}, {name: this.$t('public.delete'), type: 'delete', class: 'delete'}]
              } else if (one.status === 'exportSuccess') {
                one.statusName = this.$t('webchat.exportSuccess')
                one.operate = [{name: this.$t('public.download'), type: 'download'}]
              } else if (one.status === 'export' || one.status === 'wait') {
                one.statusName = this.$t('webchat.exportOuting')
                one.operate = []
              } else if (one.status === 'ready') {
                one.statusName = this.$t('webchat.exportWaitProcessing')
                one.operate = [{name: this.$t('public.delete'), type: 'delete', class: 'delete'}]
              } else if (one.status === 'expired') {
                one.statusName = this.$t('webchat.exportFailure')
                one.operate = [{name: this.$t('business.repeatExport'), type: 'repeatExport'}, {name: this.$t('public.delete'), type: 'delete', class: 'delete'}]
              }
            }
            this.tableData = list
          }
        })
      }
    },
    beforeRouteEnter (to, from, next) {
      next(vm => {
        vm.$store.dispatch('getCache', {type: 'agents'}).then(() => {
          vm.search()
        })
      })
    },
    beforeMount () {
      let limitNum = this.$getCache('exportTaskLimit') || {}
      this.tipNum.maxNum = limitNum.business
      this.tipNum.taskNum = 50000
      // this.$store.dispatch('getCache', {type: 'agents'}).then(() => {
      //   this.search()
      // })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .custom-search
    height 100%
    overflow auto
  h4
    line-height 40px
    border-bottom 1px solid $c-border1
    padding 0 20px
    font-weight bold
  .refresh
    color $c-main
    float right
    cursor pointer
  .prompt
    color $c-prompt
    padding-bottom 10px
  .table-wrap
    padding 10px 20px
</style>
